<template>
	<view
		style="background-color: #fff;z-index: 111;position: fixed; width: 100%;line-height: 44px;padding-top: 45px;text-align: center;z-index: 9999999;">
		<u-icon name="arrow-left" style="float:left;margin-top: 20rpx;margin-left: 10rpx;" size="36"
			@click="jump('pages/index/index')"></u-icon>
		睡眠分析
	</view>
	<view class="body">
		<view class="bg">
			<image :src="$IMAGE_BASE_URL + '/img/new/shuimianbg.png'"
				style="width: 100%; height:671rpx;margin: auto; display: block;"></image>
		</view>
		<view
			style="margin-bottom: 10px;background-color: #98E8C1;padding: 10px; z-index: 111;position: relative;margin-top: 89px;">
			<u-row>
				<u-col span="6">
					<view style="text-align: center;"
						@click="jump('pages/chart/HealthReport/index',{iotDeviceId:iotDeviceId})">
						睡眠详情
					</view>
				</u-col>
				<u-col span="6">
					<view style="background-color: #fff;width: 100%; line-height: 52rpx; text-align: center;">
						睡眠统计
					</view>
				</u-col>
			</u-row>
		</view>
		<view class="container">
			<view class="pingfenbody">
				<view class="title" style="overflow: hidden; z-index: 99999999;position: relative;text-align: center;">
					<!-- <view @click="show = true">{{$u.timeFormat(startTime, 'yyyy年mm月dd日')}}<u-icon name="arrow-down-fill"
							color="#646464" size="28"></u-icon></view>
					<u-calendar v-model="show" @change="change"></u-calendar> -->
					<picker mode="date" fields='month' :value="$u.timeFormat(endTime, 'yyyy-mm')" :start="startDate"
						:end="endDate" @change="bindDateChange">
						<view class="uni-input dateText">
							{{$u.timeFormat(endTime, 'yyyy-mm')}}<u-icon name="arrow-down-fill" color="#646464"
								size="28"></u-icon>
						</view>
					</picker>
				</view>
			</view>
			<view class="container-wrap">
				<!-- <echarts ref="echarts" :option="option" canvasId="echarts"></echarts> -->
				<lechart ref="echarts"></lechart>
			</view>
		</view>
		<view class="content">
			<view>月平均睡眠</view>
			<u-row customStyle="padding:20rpx">
				<u-col span="6">
					<view style="border-right: 1px solid #959595; margin-right: 20rpx;">
						<view style="padding:10rpx;">
							<view class="hour">{{calculateAverage(monthDataYuan.sleepQualityScore)}}<text
									class="danwei">分</text></view>
						</view>
						<u-rate :current="calculateAverage(monthDataYuan.sleepQualityScore)/20" readonly
							active-color="#fde724" :disabled="true"></u-rate>
						<!-- <view style="color: #959595;font-size: 18rpx;">超过了95%的用户</view> -->
					</view>
				</u-col>
				<u-col span="6">
					<view><text style="font-size: 24rpx;">您本月平均睡眠质量{{calculateAverage(monthDataYuan.sleepQualityScore)}}分，
							平均睡眠时长{{calculateAverage(monthDataYuan.effectiveSleepDuration,true)}}，请继续加油！</text></view>
				</u-col>
			</u-row>
			<view :class="listClass(evaluateLength((monthPJ.eyeMoveDuration/sleepTime*100).toFixed(0),20,25))">
				<view class="fl">
					<view class="shiji">快速眼动：{{formatSecondsToTime(monthPJ.eyeMoveDuration)}}</view>

					<view class="jianyi">{{(monthPJ.eyeMoveDuration/sleepTime*100).toFixed(0)}}%(建议:20%~25%)</view>
				</view>
				<view class="fr">{{evaluateLength((monthPJ.eyeMoveDuration/sleepTime*100).toFixed(0),20,25)}}</view>
			</view>
			<view :class="listClass(evaluateLength(monthPJ.effectiveSleepDuration/3600,7,10))">
				<view class="fl">
					<view class="shiji">有效睡眠时长：{{formatSecondsToTime(monthPJ.effectiveSleepDuration)}}</view>
					<view class="jianyi">建议7-10小时</view>
				</view>
				<view class="fr">{{evaluateLength(monthPJ.effectiveSleepDuration/3600,7,10)}}</view>
			</view>
			<view :class="listClass(evaluateLength((monthPJ.deepSleepDuration/sleepTime*100).toFixed(0),20,60))">
				<view class="fl">
					<view class="shiji">深睡时长：{{formatSecondsToTime(monthPJ.deepSleepDuration)}}</view>
					<view class="jianyi">{{(monthPJ.deepSleepDuration/sleepTime*100).toFixed(0)}}%建议：20%-60%</view>
				</view>
				<view class="fr">{{evaluateLength((monthPJ.deepSleepDuration/sleepTime*100).toFixed(0),20,60)}}</view>
			</view>
			<view :class="listClass(evaluateLength((monthPJ.LightSleepDuration/sleepTime*100).toFixed(0),20,60))">
				<view class="fl">
					<view class="shiji">浅睡时长：{{formatSecondsToTime(monthPJ.LightSleepDuration)}}</view>
					<view class="jianyi">{{(monthPJ.LightSleepDuration/sleepTime*100).toFixed(0)}}%建议：20%-60%</view>
				</view>
				<view class="fr">{{evaluateLength((monthPJ.LightSleepDuration/sleepTime*100).toFixed(0),20,60)}}</view>
			</view>
			<view class="list">
				<view class="fl">
					<view class="shiji">清醒时长：{{formatSecondsToTime(monthPJ.soberDuration)}}</view>
					<!-- <view class="jianyi">包括中途离床时长</view> -->
				</view>
				<!-- <view class="fr">正常</view> -->
			</view>
			<view class="list">
				<view class="fl">
					<view class="shiji">清醒次数：{{calculateAverage(monthData.soberSum)}}</view>
					<!-- <view class="jianyi">包括中途离床时长</view> -->
				</view>
				<!-- <view class="fr">正常</view> -->
			</view>
			<view class="list">
				<view class="fl">
					<view class="shiji">呼吸质量：{{calculateAverage(monthData.respiratoryQuality)}}</view>
					<!-- <view class="jianyi">包括中途离床时长</view> -->
				</view>
				<!-- <view class="fr">正常</view> -->
			</view>

		</view>
	</view>
</template>

<script>
	import {
		getCurrentPage
	} from '@/core/app'
	import {
		device
	} from "@/api/login/index.js";
	import {
		historyPropert
	} from "@/api/device/index.js";
	import StorageUtils from "@/utils/StorageUtils";
	// 条件编译引入小程序专用代码
	import lechart from "@/pages/chart/components/lime-echart/components/l-echart/l-echart.vue";
	import * as echarts from '../components/echarts.esm.min.js'
	export default {
		components: {
			lechart,
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		data() {
			return {
				startTime: 0,
				endTime: Date.parse(new Date()),
				option: {},
				monthDataYuan: {
					sleepQualityScore: [0],
					eyeMoveDuration: [0],
					effectiveSleepDuration: [0],
					deepSleepDuration: [0],
					LightSleepDuration: [0],
					soberDuration: [0],
					soberSum: [0],
					respiratoryQuality: [0],
					time: [0],
				},
				monthData: {
					sleepQualityScore: [0],
					eyeMoveDuration: [0],
					effectiveSleepDuration: [0],
					deepSleepDuration: [0],
					LightSleepDuration: [0],
					soberDuration: [0],
					soberSum: [0],
					respiratoryQuality: [0],
					time: [0],
				},
				//平均数据
				monthPJ: {
					sleepQualityScore: 1,
					eyeMoveDuration: 1,
					effectiveSleepDuration: 1,
					deepSleepDuration: 1,
					LightSleepDuration: 1,
					soberDuration: 1,
					soberSum: 1,
					respiratoryQuality: 1,
				},
				//睡眠时间
				sleepTime: 1
			};
		},
		onLoad() {
			this.startTime = this.getStartOfMonthTimestamp();
		},
		onReady() {
			this.iotDeviceId = getCurrentPage().query.iotDeviceId;
			// this.startTime= this.getStartOfMonthTimestamp();
			this.load()
		},
		methods: {
			jump(url, data) {
				this.$navTo(url, data, 'redirectTo')
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindDateChange: function(e) {
				let date = e.detail.value.split('-')
				this.startTime = new Date(date[0] * 1, date[1] * 1 - 1, 1, 0, 0, 0, 0).getTime();
				this.endTime = new Date(date[0] * 1, date[1] * 1, 0, 23, 59, 59).getTime();
				this.load()
			},
			listClass(val) {
				if (val == '正常') {
					return 'list';
				} else {
					return 'list warning';
				}
			},
			evaluateLength(value, minValue, maxValue) {
				if (value < minValue) {
					return "偏短";
				} else if (value > maxValue) {
					return "偏长";
				} else {
					return "正常";
				}
			},
			getStartOfMonthTimestamp() {
				// 创建一个新的Date对象，表示当前日期和时间
				const now = new Date();
				// 将日期设置为当前月份的第一天
				now.setDate(1);
				// 获取时间戳（毫秒）
				const timestamp = now.getTime();
				return timestamp;
			},
			fillMissingDates(data) {
				const {
					time,
					...rest
				} = data;

				// 如果 time 为空，返回整个月的数据，所有字段填充 null 或 0
				if (!time || time.length === 0) {
					const month = new Date().getMonth() + 1; // 默认当前月（可调整）
					const allDates = this.generateAllDatesInMonth(month);
					const emptyData = {
						time: allDates
					};

					Object.keys(rest).forEach(key => {
						emptyData[key] = allDates.map(() =>
							key === "soberSum" ? 0 : 0 // 假设 soberSum 是数值类型，填充 0；其他填充 null
						);
					});

					return emptyData;
				}

				// 提取月份（假设所有 time 都是同一个月）
				const month = parseInt(time[0].split("-")[0]);
				const allDates = this.generateAllDatesInMonth(month);

				// 初始化结果数据
				const result = {
					time: []
				};
				Object.keys(rest).forEach(key => {
					result[key] = [];
				});

				// 遍历当月所有日期
				allDates.forEach(date => {
					const indices = time.map((d, i) => d === date ? i : -1).filter(i => i !== -1);

					if (indices.length > 0) {
						// 如果日期存在，保留所有记录
						result.time.push(date);
						Object.keys(rest).forEach(key => {
							result[key].push(...indices.map(i => rest[key][i]));
						});
					} else {
						// 如果日期不存在，填充 0
						result.time.push(date);
						Object.keys(rest).forEach(key => {
							result[key].push(0);
						});
					}
				});

				return result;
			},
			// 生成某个月的所有日期（格式："MM-DD"）
			generateAllDatesInMonth(month) {
				const year = new Date().getFullYear(); // 默认当前年（可调整）
				const lastDay = new Date(year, month, 0).getDate(); // 当月最后一天
				const dates = [];

				for (let day = 1; day <= lastDay; day++) {
					const dateStr = `${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
					dates.push(dateStr);
				}

				return dates;
			},
			load() {
				historyPropert({
					deviceId: getCurrentPage().query.iotDeviceId,
					startTime: this.startTime,
					endTime: this.endTime,
					current: 1,
					size: 10000000,
					identifier: 'report',
					minute:true,
					load:true,
				}).then(res => {
					let report = res.obj.records;
					let monthData = {
						sleepQualityScore: [],
						eyeMoveDuration: [],
						effectiveSleepDuration: [],
						deepSleepDuration: [],
						LightSleepDuration: [],
						soberDuration: [],
						soberSum: [],
						respiratoryQuality: [],
						time: []
					}
					if (res.obj.records.length != 0) {
						report.map(val => {
							monthData.time.push(this.$u.timeFormat(val.time, 'mm-dd'))
							val = JSON.parse(val.value)
							monthData.sleepQualityScore.push(val.sleepQualityScore)
							monthData.eyeMoveDuration.push(val.eyeMoveDuration)
							monthData.effectiveSleepDuration.push(val.effectiveSleepDuration)
							monthData.deepSleepDuration.push(val.deepSleepDuration)
							monthData.LightSleepDuration.push(val.LightSleepDuration)
							monthData.soberDuration.push(val.soberDuration)
							monthData.soberSum.push(val.soberSum)
							monthData.respiratoryQuality.push(val.respiratoryQuality)
						})
						// console.log(monthData);
						this.monthPJ = {
							sleepQualityScore: this.calculateAverage(monthData.sleepQualityScore),
							eyeMoveDuration: this.calculateAverage(monthData.eyeMoveDuration),
							effectiveSleepDuration: this.calculateAverage(monthData.effectiveSleepDuration),
							deepSleepDuration: this.calculateAverage(monthData.deepSleepDuration),
							LightSleepDuration: this.calculateAverage(monthData.LightSleepDuration),
							soberDuration: this.calculateAverage(monthData.soberDuration),
							soberSum: this.calculateAverage(monthData.soberSum),
							respiratoryQuality: this.calculateAverage(monthData.respiratoryQuality)
						}
						this.sleepTime = this.calculateAverage(monthData.effectiveSleepDuration) * 1 + this
							.calculateAverage(monthData.eyeMoveDuration) * 1
					}
					this.monthDataYuan = monthData
					monthData = this.fillMissingDates(monthData);
					this.monthData = monthData
					var series = [{
							data: monthData.deepSleepDuration,
							type: 'bar',
							stack: 'a',
							name: '深睡',
							barMaxWidth: 10
						},
						{
							data: monthData.LightSleepDuration,
							type: 'bar',
							stack: 'a',
							name: '浅睡',
							barMaxWidth: 10
						},
						{
							data: monthData.soberDuration,
							type: 'bar',
							stack: 'a',
							name: '清醒',
							barMaxWidth: 10
						},
						{
							data: monthData.eyeMoveDuration,
							type: 'bar',
							stack: 'a',
							name: '眼动',
							barMaxWidth: 10
						},
					];
					const stackInfo = {};
					for (let i = 0; i < series[0].data.length; ++i) {
						for (let j = 0; j < series.length; ++j) {
							const stackName = series[j].stack;
							if (!stackName) {
								continue;
							}
							if (!stackInfo[stackName]) {
								stackInfo[stackName] = {
									stackStart: [],
									stackEnd: []
								};
							}
							const info = stackInfo[stackName];
							const data = series[j].data[i];
							if (data && data !== '-') {
								if (info.stackStart[i] == null) {
									info.stackStart[i] = j;
								}
								info.stackEnd[i] = j;
							}
						}
					}
					for (let i = 0; i < series.length; ++i) {
						const data = series[i].data;
						const info = stackInfo[series[i].stack];
						for (let j = 0; j < series[i].data.length; ++j) {
							// const isStart = info.stackStart[j] === i;
							const isEnd = info.stackEnd[j] === i;
							const topBorder = isEnd ? 20 : 0;
							const bottomBorder = 0;
							data[j] = {
								value: data[j],
								itemStyle: {
									borderRadius: [topBorder, topBorder, bottomBorder, bottomBorder]
								}
							};
						}
					}
					this.option = {
						color: ['#079c42', '#66de96', '#fca130', '#feeb3d'],
						legend: {
						    data: ['深睡', '浅睡', '清醒', '眼动']
						 },
						grid: {
							left: 5,
							right: 5,
							top: 25,
							bottom: 35
						},
						tooltip: {
							trigger: 'axis',
							top: 0,
							valueFormatter: (value) => this.formatSecondsToTime(value, 'chart'),
              confine: true,
              position: function(pt) {
                return [pt[0], '10%'];
              },
            },
						xAxis: {
							type: 'category',
							data: this.monthData.time
						},
						yAxis: {
							show: false
						},
						series: series
					};
					this.$refs.echarts.init(echarts, chart => {
						chart.setOption(this.option);
					});
					// this.$refs.echarts2.init(echarts, chart => {
					// 	chart.setOption(option);
					// });
				})
			},
			getServerData() {
				//模拟从服务器获取数据时的延时
				setTimeout(() => {

				}, 500);
			},
			formatSecondsToTime(seconds, chart) {
				if (seconds == 0) {
					return '无'
				}
				// 计算小时数
				var hours = Math.floor(seconds / 3600);
				// 计算剩余的分钟数
				var minutes = Math.floor((seconds % 3600) / 60);
				// 如果小时数为0，则小时部分不显示（可选）
				if (chart) {
					var timeString = (hours > 0 ? hours + ':' : '') + minutes.toString().padStart(2, '0');
					return timeString;
				} else {
					var timeString = (hours > 0 ? hours + '小时' : '') + minutes.toString().padStart(2, '0');
					return timeString + '分钟';
				}
			},
			formatSecondsToTime(seconds, chart) {
				if (seconds == 0) {
					return '无'
				}
				// 计算小时数
				var hours = Math.floor(seconds / 3600);
				// 计算剩余的分钟数
				var minutes = Math.floor((seconds % 3600) / 60);
				// 如果小时数为0，则小时部分不显示（可选）
				if (chart) {
					var timeString = (hours > 0 ? hours + ':' : '') + minutes.toString().padStart(2, '0');
					return timeString;
				} else {
					var timeString = (hours > 0 ? hours + '小时' : '') + minutes.toString().padStart(2, '0');
					return timeString + '分钟';
				}
			},
			calculateAverage(numbers, formatSecondsToTime) {
				
				if (!Array.isArray(numbers) || numbers.length === 0) {
					return 0
					// throw new Error("Input must be a non-empty array of numbers.");
				}

				let sum = 0;
				for (let i = 0; i < numbers.length; i++) {
					if (typeof numbers[i] !== 'number') {
						throw new Error("All elements in the array must be numbers.");
					}
					sum += numbers[i];
				}
				if (formatSecondsToTime) {
					return this.formatSecondsToTime((sum / numbers.length).toFixed(0))
				} else {
					return (sum / numbers.length).toFixed(0);
				}

			},
		}
	}
</script>
<style lang="scss">
	.body {
		min-height: 100vh;
		background-color: #f4f8fb;
		padding: 30rpx;
	}

	.bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}

	.charts-box {
		width: 100%;
		height: 100rpx;
	}

	.charts-box2 {
		width: 100%;
		height: 300rpx;
	}

	.date-btn {
		width: 90%;
		margin: 6rpx auto;
		background-color: #e4e7f8;
		border: #e4e7f8;
	}

	.date-btn-active {
		background-color: #fff;
	}

	.jianbian {
		border-radius: 50%;
		overflow: hidden;
		width: 300px;
		background: linear-gradient(to top right, #dcf0fb, #3fbaff);
		height: 230rpx;
		width: 230rpx;
		text-align: center;
		font-size: 24rpx;
		margin: auto;

		.biaoqian {
			width: 90rpx;
			margin: auto;
			background-color: #28b9ff;
			color: #fff;
			border-radius: 6rpx;
			line-height: 40rpx;
		}

		.pingfen {
			height: 150rpx;
			width: 150rpx;
			margin: 20rpx auto;
			background-color: #fff;
			border-radius: 50%;
			padding: 20rpx;
		}
	}

	.date-info {
		font-size: 24rpx;
		padding-left: 20rpx;

		image {
			margin-right: 10rpx;
			float: left;
		}

		.title {
			color: #646464;
			display: flex;
		}

		.chaoguo {
			color: #959595;
			padding: 30rpx 0;
			line-height: 30rpx;

		}

		.info {
			.w50 {
				width: 50%;
				float: left;
				margin-bottom: 10rpx;
			}

			.fl {
				float: left;
				line-height: 36rpx;

				.name {
					color: #959595;
				}

				.fwb {
					font-weight: bold;
				}
			}
		}
	}

	.content {
		background-color: #fff;
		box-shadow: 0px 0px 20rpx rgba(0, 0, 0, 0.5);
		border-radius: 20rpx;
		padding: 20rpx;
		line-height: 40rpx;
		margin-bottom: 30rpx;

		.hour {
			font-size: 58rpx;
			margin: 40rpx 0 10rpx 0;
		}

		.danwei {
			font-size: 22rpx;
		}

		.sleep-time:first-child {
			margin-top: 20rpx;
		}

		.sleep-time {
			display: flex;
			font-size: 24rpx;
			line-height: 24rpx;
			margin-bottom: 20rpx;

			.yuan {
				border-radius: 50%;
				height: 24rpx;
				width: 24rpx;
				margin-right: 20rpx;
			}

			.yuan1 {
				background-color: #842cdf;
			}

			.yuan2 {
				background-color: #d26cff;
			}

			.yuan3 {
				background-color: #ff7a75;
			}

			.name {
				margin-right: 50rpx;
			}

			.bfb {
				color: #959595;
				margin-left: 20rpx;
			}
		}
	}

	.list {
		margin: 10rpx;
		padding: 10rpx;
		overflow: hidden;

		.fl {
			float: left;
			font-size: 26rpx;

			.jianyi {
				font-size: 24rpx;
				color: #959595;
			}
		}

		.fr {
			margin-right: 20rpx;
			float: right;
			line-height: 80rpx;
			color: #07a1eb;
		}

	}

	.list.warning {
		background-color: #feecea;
		border-radius: 10rpx;

		.fr {
			color: #ff4039;
		}
	}

	.tu {
		.fr {
			float: right;
			color: #07a1eb;
			margin-right: 40rpx;
		}

		.red {
			color: #ff4039;
		}
	}

	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.container-wrap {
		width: 100%;
		height: 500rpx;
	}
</style>